import * as ww from '@wecom/jssdk';
import {
	agentSign,
	configSign
} from '../common/api/chat';

class WechatWorkSdkManager {
	constructor(options = {}) {
		this.corpId = options.corpId || '';
		this.agentId = options.agentId || '';
		this.jsApiList = options.jsApiList || [
			'openEnterpriseChat',
			'selectExternalContact',
			'getExternalContact',
			'shareToExternalContact'
			// 其他需要使用的 API
		];
		this.isSdkReady = false;
		this.initSdk();
	}


	async initSdk() {
		try {
			await ww.register({
				corpId: this.corpId,
				agentId: this.agentId,
				jsApiList: this.jsApiList,
				getConfigSignature: this.getConfigSignature.bind(this), // 企业签名
				getAgentConfigSignature: this.getAgentConfigSignature.bind(this) // 应用签名
			});

			this.isSdkReady = true;
			console.log('企业微信 JS-SDK 初始化成功');
		} catch (error) {
			console.error('企业微信 JS-SDK 初始化失败:', error);
			throw error;
		}
	}

	getPureUrl() {
		let fullUrl = window.location.href;
		// 剔除 # 及后续内容
		const hashIndex = fullUrl.indexOf('#');
		if (hashIndex !== -1) fullUrl = fullUrl.slice(0, hashIndex);
		// 剔除 ? 及后续内容
		const queryIndex = fullUrl.indexOf('?');
		if (queryIndex !== -1) fullUrl = fullUrl.slice(0, queryIndex);
		return fullUrl;
	}

	async getConfigSignature(url) {
		try {
			const currentUrl = this.getPureUrl();
			console.log(currentUrl, '---currentUrl');
			const response = await configSign({
				url: currentUrl
			});

			if (response.code != 200) {
				throw new Error(`HTTP error! status: ${response}`);
			}

			const data = await response.data;

			return {
				timestamp: data.timestamp,
				nonceStr: data.nonceStr,
				signature: data.signature
			};
		} catch (error) {
			console.error('获取企业签名失败:', error);
			throw error;
		}
	}

	// 应用
	async getAgentConfigSignature(url) {
		try {
			const currentUrl = this.getPureUrl();
			console.log(currentUrl, '---currentUrl');
			const response = await agentSign({
				url: currentUrl
			})

			if (response.code != 200) {
				throw new Error(`HTTP error! status: ${response}`);
			}

			const data = await response.data;

			return {
				timestamp: data.timestamp,
				nonceStr: data.nonceStr,
				signature: data.signature
			};
		} catch (error) {
			console.error('获取应用签名失败:', error);
			throw error;
		}
	}

	/**
	 * 等待 SDK 准备就绪
	 * @param {number} timeout - 超时时间（毫秒）
	 * @returns {Promise<boolean>}
	 */
	async waitForReady(timeout = 5000) {
		if (this.isSdkReady) {
			return true;
		}

		return new Promise((resolve, reject) => {
			const startTime = Date.now();
			const checkInterval = setInterval(() => {
				if (this.isSdkReady) {
					clearInterval(checkInterval);
					resolve(true);
				} else if (Date.now() - startTime > timeout) {
					clearInterval(checkInterval);
					reject(new Error('SDK 初始化超时'));
				}
			}, 100);
		});
	}

	/**
	 * 打开企业微信会话（需要应用签名）
	 * @param {Object} params - 会话参数
	 * @returns {Promise<Object>}
	 */
	async openEnterpriseChat(params) {
		await this.waitForReady();

		return new Promise((resolve, reject) => {
			ww.openEnterpriseChat({
				...params,
				success: (res) => {
					console.log('打开会话成功:', res);
					resolve(res);
				},
				fail: (err) => {
					console.error('打开会话失败:', err);
					reject(err);
				}
			});
		});
	}

	/**
	 * 选择外部联系人（需要应用签名）
	 * @returns {Promise<Object>}
	 */
	async selectExternalContact() {
		await this.waitForReady();

		return new Promise((resolve, reject) => {
			ww.selectExternalContact({
				success: (res) => {
					console.log('选择外部联系人成功:', res);
					resolve(res);
				},
				fail: (err) => {
					console.error('选择外部联系人失败:', err);
					reject(err);
				}
			});
		});
	}

	/**
	 * 获取外部联系人（需要企业签名）
	 * @param {string} externalUserId - 外部联系人ID
	 * @returns {Promise<Object>}
	 */
	async getExternalContact(externalUserId) {
		await this.waitForReady();

		return new Promise((resolve, reject) => {
			ww.getExternalContact({
				externalUserId,
				success: (res) => {
					console.log('获取外部联系人成功:', res);
					resolve(res);
				},
				fail: (err) => {
					console.error('获取外部联系人失败:', err);
					reject(err);
				}
			});
		});
	}

	/**
	 * 分享到外部联系人（需要企业签名）
	 * @param {Object} shareInfo - 分享信息
	 * @returns {Promise<Object>}
	 */
	async shareToExternalContact(shareInfo) {
		await this.waitForReady();

		return new Promise((resolve, reject) => {
			ww.shareToExternalContact({
				...shareInfo,
				success: (res) => {
					console.log('分享成功:', res);
					resolve(res);
				},
				fail: (err) => {
					console.error('分享失败:', err);
					reject(err);
				}
			});
		});
	}

	/**
	 * 通用 API 调用方法
	 * @param {string} apiName - API 名称
	 * @param {Object} params - 参数
	 * @returns {Promise<Object>}
	 */
	async callApi(apiName, params = {}) {
		await this.waitForReady();

		return new Promise((resolve, reject) => {
			if (typeof ww[apiName] !== 'function') {
				reject(new Error(`API ${apiName} 不存在`));
				return;
			}

			ww[apiName]({
				...params,
				success: (res) => resolve(res),
				fail: (err) => reject(err)
			});
		});
	}

	/**
	 * 检查 API 是否可用
	 * @param {string} apiName - API 名称
	 * @returns {Promise<boolean>}
	 */
	async checkApiAvailability(apiName) {
		await this.waitForReady();

		return new Promise((resolve) => {
			ww.invoke('checkJsApi', {
				jsApiList: [apiName],
				success: (res) => {
					const isAvailable = res.checkResult[apiName];
					resolve(!!isAvailable);
				},
				fail: () => resolve(false)
			});
		});
	}
}

// 创建单例实例
const wechatWorkSdkManager = new WechatWorkSdkManager({
	corpId: 'ww36f98ef0549bac0e',
	agentId: 1000002,
	jsApiList: [
		'openEnterpriseChat',
		'selectExternalContact',
		'getExternalContact',
		'shareToExternalContact',
		'scanQRCode'
	]
});

export default wechatWorkSdkManager;